package com.dc.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dc.service.UsersService;
import com.dc.service.impl.UsersServiceImpl;
import com.dc.tools.MD5Util;
import com.dc.tools.PageData;
import com.dc.tools.SendSms;
import com.google.gson.Gson;
import com.dc.comments.AjaxResponse;
import com.dc.entity.Users;

/**
 * Servlet implementation class UsersServlet
 */
@WebServlet("/UsersServlet")
public class UsersServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	UsersService usersService = new UsersServiceImpl();

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UsersServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		// 设置请求编码
		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("utf-8");

		String op = "";
		if (request.getParameter("op") != null) {
			op = request.getParameter("op");
			System.out.println("op:" + op);
			if ("".equals(op)) {
				// 分页显示用户信息
				doSelectUsersByPage(request, response);
			} else if ("usersRegister".equals(op)) {
				// 用户注册
				doUsersRegister(request, response);
			} else if ("selectUsersByPage".equals(op)) {
				// 分页显示用户信息
				doSelectUsersByPage(request, response);
			} else if ("selectUsersByKeyword".equals(op)) {
				// 根据关键词搜索用户
				doSelectUsersByKeyword(request, response);
			} else if ("addUsers".equals(op)) {
				// 管理员添加用户
				doAddUsers(request, response);
			} else if ("updateUsers".equals(op)) {
				// 修改用户信息
				doUpdateUsers(request, response);
			} else if ("deleteUsers".equals(op)) {
				// 删除用户信息（ajax）
				doDeleteUsers(request, response);
			} else if ("ajaxUsername".equals(op)) {
				// 验证输入的用户名是否已被使用（ajax）
				doAjaxUsername(request, response);
			} else if ("resetUserspsw".equals(op)) {
				// 重置用户密码（ajax）
				doResetUserpsw(request, response);
			} else if ("ajaxSendmsg".equals(op)) {
				// 获取验证码
				doAjaxSendMsg(request, response);
			} else if ("ajaxPhone".equals(op)) {
				// 验证输入的手机号是否已被使用
				doAjaxUserphone(request, response);
			}
		}
	}

	/**
	 * 用户注册
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doUsersRegister(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1获取参数，需要判断是否为空
		String op = "";
		if (request.getParameter("op") != null) {
			op = request.getParameter("op");
		}
		System.out.println("op:" + op);
		String username = "";
		if (request.getParameter("username") != null) {
			username = request.getParameter("username");
		}
		String userpsw = "";
		if (request.getParameter("userpsw") != null) {
			// 使用MD5算法将密码转换成密文
			userpsw = MD5Util.getEncodeByMd5(request.getParameter("userpsw"));
			System.out.println(userpsw);
		}
		String conuserpsw = "";
		if (request.getParameter("conuserpsw") != null) {
			conuserpsw = MD5Util.getEncodeByMd5(request.getParameter("conuserpsw"));
		}
		String userphone = "";
		if (request.getParameter("userphone") != null) {
			userphone = request.getParameter("userphone");
		}
		String useremail = "";
		if (request.getParameter("useremail") != null) {
			useremail = request.getParameter("useremail");
		}
		String useraddress = "";
		if (request.getParameter("useraddress") != null) {
			useraddress = request.getParameter("useraddress");
		}
		// [重复提交判断]判断表单是否重复提交
		// a取出存储在session中的token
		String tokenSession = (String) request.getSession().getAttribute("token");
		// b取出表单提交的token
		String tokenRequest = request.getParameter("token");
		// c重复提交的判断
		// session中没有token、表单数据中没有token、session中的token和表单提交的token不同，都是表单提交重复
		if (tokenSession == null || tokenRequest == null || !tokenSession.equals(tokenRequest)) {
			// 重复提交
			request.setAttribute("msg", "表单已提交，请勿刷新！");
			request.getRequestDispatcher("users_register.jsp").forward(request, response);
		} else {
			if (!userpsw.equals(conuserpsw)) {
				request.setAttribute("msg", "两次密码输入不一致！");
				request.getRequestDispatcher("users_register.jsp").forward(request, response);
			} else {
				// 2构造Users对象
				Users users = new Users(username, userpsw, userphone, useremail, useraddress);
				// 3调用service中的方法
				boolean flag = usersService.addUsers(users);
				// 4根据返回结果进行转发或者提示
				if (flag) {
					request.setAttribute("msg", "注册成功");
					request.getRequestDispatcher("users_register.jsp").forward(request, response);

				} else {
					request.setAttribute("msg", "注册失败");
					request.getRequestDispatcher("users_register.jsp").forward(request, response);
				}
			}
		}
	}

	/**
	 * 分页显示用户信息
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doSelectUsersByPage(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 获取请求参数
		String keyword = "";
		if (request.getParameter("keyword") != null) {
			keyword = request.getParameter("keyword");
		}
		// 页码默认值为1
		int page = 1;
		// 每页默认显示10条数据
		int pageSize = 10;
		if (request.getParameter("page") != null) {
			page = Integer.parseInt(request.getParameter("page"));
		}
		if (request.getParameter("pageSize") != null) {
			pageSize = Integer.parseInt(request.getParameter("pageSize"));
		}
		PageData<Users> pd = usersService.selectUsersByPage(page, pageSize, keyword);
		request.setAttribute("pd", pd);
		request.setAttribute("keyword", keyword);
		// 转发到usersmanager.jsp
		request.getRequestDispatcher("admin_usersmanager.jsp").forward(request, response);
	}

	/**
	 * 根据关键词搜索用户信息
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doSelectUsersByKeyword(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 获取请求参数
		String keyword = "";
		if (request.getParameter("keyword") != null) {
			keyword = request.getParameter("keyword");
		}
		List<Users> list = usersService.selectUsersByKeyword(keyword);
		request.setAttribute("list", list);
		request.getRequestDispatcher("admin_usersmanager.jsp").forward(request, response);
	}

	/**
	 * 添加用户信息
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doAddUsers(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1获取参数，需要判断是否为空
		String username = "";
		if (request.getParameter("username") != null) {
			username = request.getParameter("username");
		}
		String userpsw = "";
		if (request.getParameter("userpsw") != null) {
			// 使用MD5算法将密码转换成密文
			userpsw = MD5Util.getEncodeByMd5(request.getParameter("userpsw"));
		}
		String conuserpsw = "";
		if (request.getParameter("conuserpsw") != null) {
			conuserpsw = MD5Util.getEncodeByMd5(request.getParameter("conuserpsw"));
		}
		String userphone = "";
		if (request.getParameter("userphone") != null) {
			userphone = request.getParameter("userphone");
		}
		String useremail = "";
		if (request.getParameter("useremail") != null) {
			useremail = request.getParameter("useremail");
		}
		String useraddress = "";
		if (request.getParameter("useraddress") != null) {
			useraddress = request.getParameter("useraddress");
		}
		if (!userpsw.equals(conuserpsw)) {
			request.setAttribute("msg", "两次密码输入不一致！");
			request.getRequestDispatcher("admin_usersmanager.jsp").forward(request, response);
		} else {
			// 2构造Users对象
			Users users = new Users(username, userpsw, userphone, useremail, useraddress);
			// 3调用service中的方法
			boolean flag = usersService.addUsers(users);
			System.out.println("是否添加完成" + flag);
			// 4根据返回结果进行转发或者提示
			if (flag) {
				request.setAttribute("msg", "增加成功");
				request.getRequestDispatcher("admin_usersmanager.jsp").forward(request, response);

			} else {
				request.setAttribute("msg", "增加失败");
				request.getRequestDispatcher("admin_usersmanager.jsp").forward(request, response);
			}
		}
	}

	/**
	 * 修改用户信息
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doUpdateUsers(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1获取参数，需要判断是否为空
		int userid = 0;
		if (request.getParameter("userid") != null) {
			userid = Integer.parseInt(request.getParameter("userid"));
		}
		System.out.println("userid" + userid);
		String username = "";
		if (request.getParameter("username") != null) {
			username = request.getParameter("username");
		}
		String userphone = "";
		if (request.getParameter("userphone") != null) {
			userphone = request.getParameter("userphone");
		}
		String useremail = "";
		if (request.getParameter("useremail") != null) {
			useremail = request.getParameter("useremail");
		}
		String useraddress = "";
		if (request.getParameter("useraddress") != null) {
			useraddress = request.getParameter("useraddress");
		}
		String userstatevalue = request.getParameter("userstate");
		boolean userstate = true;
		if ("true".equals(userstatevalue)) {
			userstate = true;
		} else if ("false".equals(userstatevalue)) {
			userstate = false;
		}
		// 2构造Users对象
		Users users = new Users(userid, username, userphone, useremail, useraddress, userstate);
		// 3调用service中的方法
		boolean flag = usersService.updateUsers(users);
		// 4根据返回结果进行转发或者提示
		if (flag) {
			request.setAttribute("msg", "修改成功");
			request.getRequestDispatcher("admin_usersmanager.jsp").forward(request, response);
		} else {
			request.setAttribute("msg", "修改失败");
			request.getRequestDispatcher("admin_usersmanager.jsp").forward(request, response);
		}
	}

	/**
	 * 删除用户信息（ajax）
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doDeleteUsers(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 设置响应头编码
		response.setContentType("application/json;charset=utf-8");

		// 1获取参数，需要判断是否为空
		int userid = 0;
		if (request.getParameter("userid") != null) {
			userid = Integer.parseInt(request.getParameter("userid"));
		}
		System.out.println("userid" + userid);
		// 2调用service中的方法
		boolean flag = usersService.deleteUsers(userid);
		System.out.println("是否删除成功" + flag);
		// 创建AjaxResponse对象
		AjaxResponse res = new AjaxResponse(flag + "", 200);
		// 创建Gson对象
		Gson gson = new Gson();
		String jsonString = gson.toJson(res);
		// 4.响应
		PrintWriter outPrintWriter = response.getWriter();
		outPrintWriter.print(jsonString);
		// 5.关闭
		outPrintWriter.close();
	}

	/**
	 * 重置用户密码
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void doResetUserpsw(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 设置响应头编码
		response.setContentType("application/json;charset=utf-8");

		// 1获取参数，需要判断是否为空
		int userid = 0;
		if (request.getParameter("userid") != null) {
			userid = Integer.parseInt(request.getParameter("userid"));
		}
		System.out.println("userid" + userid);
		// 重置密码为“666666”
		String userpsw = MD5Util.getEncodeByMd5("666666");
		// 2调用service中的方法
		boolean flag = usersService.resetUserpsw(userid, userpsw);
		// 创建AjaxResponse对象
		AjaxResponse res = new AjaxResponse(flag + "", 200);
		// 创建Gson对象
		Gson gson = new Gson();
		String jsonString = gson.toJson(res);
		// 4.响应
		PrintWriter outPrintWriter = response.getWriter();
		outPrintWriter.print(jsonString);
		// 5.关闭
		outPrintWriter.close();
	}

	/**
	 * 验证输入的用户名是否已被使用
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void doAjaxUsername(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 1.设置响应头的contentType
		response.setContentType("application/json;charset=utf-8");
		String username = request.getParameter("username");
		// 2调用service中的方法，查询数据库是否存在该username的用户
		Users users = usersService.selectUsersByName(username);
		String msg = "exists";
		if (users == null) {
			// 数据库中没找到相同用户名
			msg = "notexists";
		}
		AjaxResponse ajaxResponse = new AjaxResponse(msg, 200);
		// 3.将msg转换为json格式的字符串
		Gson gson = new Gson();
		String jsonString = gson.toJson(ajaxResponse);
		// 4.响应
		PrintWriter outPrintWriter = response.getWriter();
		outPrintWriter.print(jsonString);
		// 5.关闭
		outPrintWriter.close();
	}

	/**
	 * 生成手机验证码
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doAjaxSendMsg(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1.设置响应头的contentType
		response.setContentType("application/json;charset=utf-8");
		String userphone = "";
		if (request.getParameter("userphone") != null) {
			userphone = request.getParameter("userphone");
		}
		// 2生成一个六位随机数
		Random random = new Random();
		String scode = "";
		for (int i = 0; i < 6; i++) {
			scode += random.nextInt(10);
		}
		System.out.println("scode=" + scode);
		SendSms.sendSms(scode, userphone);
		Gson gson = new Gson();
		String jsonString = gson.toJson(scode);
		// 4 响应
		PrintWriter outPrintWriter = response.getWriter();
		outPrintWriter.print(jsonString);
		// 5.关闭
		outPrintWriter.close();
	}

	/**
	 * 验证输入的手机号是否已被使用
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doAjaxUserphone(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1.设置响应头的contentType
		response.setContentType("application/json;charset=utf-8");
		String userphone = request.getParameter("userphone");
		System.out.println("phone" + userphone);
		// 2.调用service中的方法，查询是否存在该手机号是该userphone的用户
		Users users = usersService.selectUsersByPhone(userphone);
		boolean msg = true;
		// String msg = "exists";
		if (users == null) {
			// 数据库中没找到相同用户名
			msg = false;
		}
		// AjaxResponse ajaxResponse = new AjaxResponse(msg, 200);
		// 3.将msg转换为json格式的字符串
		Gson gson = new Gson();
		String jsonString = gson.toJson(msg);
		// 4.响应
		PrintWriter outPrintWriter = response.getWriter();
		outPrintWriter.print(jsonString);
		// 5.关闭
		outPrintWriter.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
